import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import STL

# 创建一个示例时间序列数据
np.random.seed(0)
dates = pd.date_range('2020-01-01', periods=100, freq='M')
data = np.sin(np.linspace(0, 3 * np.pi, len(dates))) + 0.5 * np.random.randn(len(dates)) + np.linspace(0, 1, len(dates))

# 将数据转换为Pandas DataFrame
df = pd.DataFrame(data, index=dates, columns=['value'])

# 进行STL分解
result = STL(df['value'], seasonal=11).fit()

# 绘制分解结果
plt.figure(figsize=(12, 8))
result.plot()
plt.show()

# 分别查看趋势、季节性和残差成分
trend = result.trend
seasonal = result.seasonal
residual = result.resid

# 绘制每个成分
fig, axes = plt.subplots(4, 1, figsize=(12, 12), sharex=True)

axes[0].set_title("Original Time Series")
axes[0].plot(df.index, df['value'], label='Original')
axes[0].legend(loc='upper left')

axes[1].set_title("Trend Component")
axes[1].plot(df.index, trend, label='Trend')
axes[1].legend(loc='upper left')

axes[2].set_title("Seasonal Component")
axes[2].plot(df.index, seasonal, label='Seasonal')
axes[2].legend(loc='upper left')

axes[3].set_title("Residual Component")
axes[3].plot(df.index, residual, label='Residual')
axes[3].legend(loc='upper left')

plt.tight_layout()
plt.show()